package com.uduemc.biso.node.web.component;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.uduemc.biso.core.utils.HttpUtil;
import com.uduemc.biso.node.core.common.entities.DomainRecord;
import com.uduemc.biso.node.core.property.GlobalProperties;

/**
 * ApiFunction 与 CenterFunction 的区别 ApiFunction 主要是针对其他的API接口 CenterFunction
 * 主要是针对主控端的API接口
 * 
 * @author guanyi
 *
 */
@Component
public class ApiFunction {

	private final Logger logger = LoggerFactory.getLogger(getClass());

	private static String suffix = "biso";

	@Autowired
	private GlobalProperties globalProperties;

	@Autowired
	private ObjectMapper objectMapper;

	/**
	 * 获取域名的备案信息
	 * 
	 * @param domain
	 * @return
	 */
	public DomainRecord getDomainRecordInfo(String domain) {
		String url = globalProperties.getApi().getDomainRecord();
		logger.info("getDomainRecordInfo 请求地址： " + url);
		String utime = String.valueOf(new Date().getTime()).substring(0,
				String.valueOf(new Date().getTime()).length() - 3);
		String str = domain + ApiFunction.suffix + utime;
		String ckey = DigestUtils.md5DigestAsHex(str.getBytes());

		Map<String, String> param = new HashMap<String, String>();
		param.put("domain", domain);
		param.put("utime", utime);
		param.put("ckey", ckey);
		String json = HttpUtil.post(url, param);

		DomainRecord readValue = null;
		try {
			readValue = objectMapper.readValue(json, DomainRecord.class);
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return readValue;
	}

}
